import { defineStore } from 'pinia'
import { store } from '@/store'
import { UserLoginType, UserType } from '@/api/login/types'
import { ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getUserInfoApi, loginApi, loginOutApi } from '@/api/login'
import { useTagsViewStore } from './tagsView'
import router from '@/router'
import Cookies from 'js-cookie'

interface UserState {
  userInfo?: UserType
  isUser: boolean // 是否已登录并获取到用户信息
  tokenKey: string
  token: string
  refreshToken: string
  roleRouters?: string[] | AppCustomRouteRecordRaw[]
  loginInfo?: UserLoginType
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      isUser: false,
      tokenKey: 'Cookie',
      token: '',
      refreshToken: '',
      roleRouters: undefined,
      loginInfo: undefined
    }
  },
  getters: {
    getTokenKey(): string {
      return this.tokenKey
    },
    getToken(): string {
      return this.token
    },
    getRefreshToken(): string {
      return this.refreshToken
    },
    getIsUser(): boolean {
      return this.isUser
    },
    getUserInfo(): UserType | undefined {
      return this.userInfo
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return this.roleRouters
    },
    getLoginInfo(): UserLoginType | undefined {
      return this.loginInfo
    },
    getUserStr(): string {
      const info = this.userInfo
      return `${info?.username}(${info?.userCode})`
    }
  },
  actions: {
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
    },
    setToken(token: string) {
      this.token = token
    },
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken
    },
    async setUserInfo() {
      await getUserInfoApi().then((res) => {
        this.isUser = true
        this.userInfo = res.data
      })
    },
    setRoleRouters(roleRouters: string[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = roleRouters
    },
    async login(formData: UserLoginType) {
      const res = await loginApi(formData)
      if (res) {
        this.setLoginInfo(undefined)
        // this.setAuthInfo(res.data)
        this.isUser = true
        this.userInfo = res.data
      }
      return res
    },
    // async refresh() {
    //   // 刷新Token
    //   const res = await refreshTokenApi(this.getRefreshToken)
    //   if (res) {
    //     this.setAuthInfo(res.data)
    //   }
    // },
    // setAuthInfo(data: LoginResponseType) {
    //   this.setToken(`${data.token_type} ${data.access_token}`)
    //   this.setRefreshToken(data.refresh_token || this.getRefreshToken)
    // },
    logoutConfirm() {
      const { t } = useI18n()
      ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
        .then(async () => {
          const res = await loginOutApi()
          if (res) {
            this.reset()
          }
        })
        .catch(() => {})
    },
    reset() {
      const tagsViewStore = useTagsViewStore()
      tagsViewStore.delAllViews()
      this.setToken('')
      this.setRefreshToken('')
      Cookies.remove('xxl_sso_sessionid')
      this.isUser = false
      this.userInfo = undefined
      this.setRoleRouters([])
      router.replace('/login').then(() => {})
    },
    async logout() {
      this.reset()
    },
    setLoginInfo(loginInfo: UserLoginType | undefined) {
      this.loginInfo = loginInfo
    }
  },
  persist: true
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
